<?php

namespace App\Http\Controllers\API;

use App\Criteria\RolesCriteria;
use App\Http\Requests\API\CreateUserAPIRequest;
use App\Http\Requests\API\UpdateUserAPIRequest;
use App\Models\User;
use App\Repositories\UserRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

/**
 * Class UserController
 * @package App\Http\Controllers\API
 */
class UserAPIController extends AppBaseController
{
    /** @var  UserRepository */
    private $userRepository;

    public function __construct(UserRepository $userRepo)
    {
        $this->userRepository = $userRepo;
    }

    /**
     * Display a listing of the User.
     * GET|HEAD /users
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {

        $this->userRepository->pushCriteria(new RolesCriteria());
        $this->userRepository->pushCriteria(new RequestCriteria($request));
        $this->userRepository->pushCriteria(new LimitOffsetCriteria($request));

        $users = $this->userRepository->paginate($request->limit);
        return $this->sendResponse($users->toArray(), '查询成功');
    }

    /**
     * Store a newly created User in storage.
     * POST /users
     *
     * @param CreateUserAPIRequest $request
     *
     * @return Response
     */
    public function store(CreateUserAPIRequest $request)
    {
        $input = $request->all();
        $input['flag'] = isset($input['flag']) && in_array($input['flag'],[0,1]) ? $input['flag']:0;
        $users = $this->userRepository->create($input);
        $users->roles()->attach($input['roles']);

        //设置默认密码
        $users->password = config('custom.default_password');
        $users->save();

        return $this->sendResponse($users->toArray(), '添加用户成功');
    }

    /**
     * 获取用户详情
     * GET|HEAD /users/{id}
     *
     * @param $id
     * @param Request $request
     * @return mixed
     */
    public function show($id, Request $request)
    {
        $this->userRepository->pushCriteria(new RequestCriteria($request));
        /** @var User $user */
        $user = $this->userRepository->findWithoutFail($id);
        if (empty($user)) {
            return $this->sendError('User not found');
        }

        return $this->sendResponse($user->toArray(), '查询用户成功');
    }

    /**
     * Update the specified User in storage.
     * PUT/PATCH /users/{id}
     *
     * @param  int $id
     * @param UpdateUserAPIRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateUserAPIRequest $request)
    {
        $input = $request->all();
        $input['flag'] = isset($input['flag']) && in_array($input['flag'],[0,1]) ? $input['flag']:0;
        /** @var User $user */
        $user = $this->userRepository->findWithoutFail($id);

        if (empty($user)) {
            return $this->sendError('用户不存在');
        }

        $user = $this->userRepository->update($input, $id);

        //更新角色
        if (isset($input['roles'])) {
            $user->roles()->sync($input['roles']);
        }

        return $this->sendResponse($user->toArray(), '修改用户成功');
    }

    /**
     * Remove the specified User from storage.
     * DELETE /users/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        /** @var User $user */
        $user = $this->userRepository->findWithoutFail($id);
        if (empty($user)) {
            return $this->sendError('用户不存在');
        }
        if ($user->name=='admin') {
            return $this->sendError('拒绝删除超级管理员');
        }
        $user->delete();

        return $this->sendResponse($id, '用户删除成功');
    }

    /**
     * Remove the specified User from storage.
     * GET /users/info
     *
     * @return mixed
     */
    public function info()
    {
        $user = Auth::user();
        $data = $user->toArray();
        $data['roles'] = $user->roles;
        $data['permissions'] = $user->getAllPermissions();

        return $this->sendResponse($data, '获取个人信息成功');
    }

    /**
     * Remove the specified User from storage.
     * PUT /users/change-password
     * @param  Request $request
     *
     * @return mixed
     */
    /**
     * Remove the specified User from storage.
     * PUT /users/change-password
     * @param  Request $request
     *
     * @return mixed
     */
    public function changePassword(Request $request)
    {
        $this->validate($request, ['password' => 'required|max:64', 'new_password' => 'required|max:64']);

        $user = Auth::user();
        if (!Hash::check($request->password, $user->password)) {
            return $this->sendError('密码输入错误');
        }

        $user->password = $request->new_password;
        $user->save();
        return $this->sendResponse([], '密码修改成功');
    }

    /**
     * Remove the specified User from storage.
     * PUT /users/change-password
     * @param  Request $request
     *
     * @return mixed
     */
    public function changePwd(Request $request)
    {
        $this->validate($request, ['password' => 'required|max:64', 'new_password' => 'required|max:64','id'=>'int']);
        $input = $request->all();
        if(empty($input['id'])){
            return $this->sendError('缺少用户id');
        }
        if(empty($input['new_password'])){
            return $this->sendError('缺少重置密码');
        }
        $user = $this->userRepository->findWithoutFail($input['id']);
        if ($request->password != $request->new_password) {
            return $this->sendError('密码输入不一致');
        }

        $user->password = $request->new_password;
        $user->save();
        return $this->sendResponse([], '密码修改成功');
    }
    /**
     * Remove the specified User from storage.
     * PUT /users/change-password
     * @param  Request $request
     *
     * @return mixed
     */
    public function changeFlag(Request $request)
    {
        $this->validate($request, ['id' => 'required|int', 'flag' => 'required|int']);
        $input = $request->all();
        $user = $this->userRepository->findWithoutFail($input['id']);
        if (empty($user)) {
            return $this->sendError('用户不存在');
        }
        if (!in_array($input['flag'], [0,1])) {
            return $this->sendError('状态错误');
        }
        $user = Auth::user();
        if($user->id == $input['id']){
            return $this->sendError('不能冻结自己');
        }
        $user = $this->userRepository->update($input, $input['id']);
        return $this->sendResponse([], '状态修改成功');
    }
}
